package com.cl.blog.web.manager;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cl.blog.annotation.Login;
import com.cl.blog.common.Const;
import com.cl.blog.common.Result;
import com.cl.blog.entity.BTag;
import com.cl.blog.service.BTagService;
import com.cl.blog.vo.BatchTag;
import com.cl.blog.vo.BatchType;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 付
 * @Date 2024-03-18 13:09
 * @Version 1.0
 * @description 标签管理接口
 * @since 1.0
 */
@RestController
@RequestMapping("/admin/tag")
public class AdminTagController {

	@Autowired
	BTagService bTagService;

	// 列表
	@GetMapping("/list")
	@Login(issuer = Const.GRADE_ADMIN)
	public Result getList() {
		List<BTag> list = bTagService.list();
		return Result.success(list);
	}

	// 删除
	@GetMapping("/delete")
	@Login(issuer = Const.GRADE_ADMIN)
	@Transactional(rollbackFor = Exception.class)
	public Result delete(Integer id) {
		BTag bTag = bTagService.getById(id);
		Assert.notNull(bTag, "抱歉，当前标签不存在");
		boolean id1 = bTagService.remove(new QueryWrapper<BTag>().eq("id", id));
		if (!id1) {
			return Result.error("系统错误，稍后再试");
		}
		return Result.success();
	}

	@GetMapping("/update")
	@Login(issuer = Const.GRADE_ADMIN)
	@Transactional(rollbackFor = Exception.class)
	public Result update(Integer id, String tagName) {
		BTag bTag = bTagService.getById(id);
		Assert.notNull(bTag, "抱歉，当前标签不存在");
		bTagService.update(new UpdateWrapper<BTag>()
				.eq("id", id)
				.set("name", tagName)
				.set("update_time", LocalDateTime.now())
		);
		return Result.success();
	}

	@GetMapping("/add")
	@Login(issuer = Const.GRADE_ADMIN)
	@Transactional(rollbackFor = Exception.class)
	public Result insert(String names) {
		boolean b = bTagService.saveName(names);
		return Result.success();
	}

	// 批量删除
	@PostMapping("/batch-delete")
	@Login(issuer = Const.GRADE_ADMIN)
	public Result batchDelete(@RequestBody List<Integer> ids) {
		System.out.println("删除的数组---" + ids);
		return Result.success(bTagService.removeBatchByIds(ids));
	}

	// 批量修改
	@PostMapping("/batch-update")
	@Login(issuer = Const.GRADE_ADMIN)
	public Result batchUpdate(@Validated @RequestBody BatchTag batchTag) {
		System.out.println("修改的数组---" + batchTag.getIds());
		System.out.println("修改的数组name---" + batchTag.getNames());
//		Assert.isTrue(batchType.getIds().size()!=batchType.getNames().size(),"抱歉，修改格式错误，可能是数量不对等");
		if (batchTag.getIds().size() != batchTag.getNames().size()) {
			return Result.error("抱歉，修改格式错误，可能是数量不对等");
		}
		return Result.success(bTagService.updateBatchType(batchTag.getIds(), batchTag.getNames()));
	}

}
